#ifndef LOGMANAGER_H
#define LOGMANAGER_H

#include <QObject>
#include <QSqlDatabase>
#include <QList>
#include <QSqlRecord>
#include <QMutex>
#include "threadpool.h"
#include <QDebug>

class LogManager;

// 记录日志的任务类
class RecordLogTask : public QRunnable {
public:
    RecordLogTask(LogManager* logManager, const QString& timestamp, const QString& logType, const QString& logLevel, const QString& content, int userId, int deviceId);
    void run() override;

private:
    LogManager* m_logManager;
    QString m_timestamp;
    QString m_logType;
    QString m_logLevel;
    QString m_content;
    int m_userId;
    int m_deviceId;
};

// 导出日志的任务类
class ExportLogTask : public QRunnable {
public:
    ExportLogTask(LogManager* logManager, const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType);
    void run() override;

private:
    LogManager* m_logManager;
    QString m_filePath;
    QString m_startTime;
    QString m_endTime;
    QString m_logType;
};

// 日志管理类，负责日志的记录、查询和导出
class LogManager : public QObject {
    Q_OBJECT
    // 声明友元类
    friend class RecordLogTask;
    friend class ExportLogTask;

public:
    // 构造函数
    explicit LogManager(QObject* parent = nullptr);
    // 析构函数
    ~LogManager();

    // 记录系统日志
    void recordSystemLog(const QString& timestamp, const QString& logType, const QString& logLevel, const QString& content, int userId, int deviceId);

    // 查询日志
    QList<QSqlRecord> queryLogs(const QString& startTime, const QString& endTime, const QString& logType);

    // 导出日志为CSV
    void exportLogsToCSV(const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType);
    // 导出日志为文本
    void exportLogsToText(const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType);

private:
    // 创建日志表
    void createLogTable();
    // 互斥锁，保证线程安全
    QMutex m_mutex;
    // 内部记录系统日志函数
    bool recordSystemLogInternal(QSqlDatabase& db, const QString& timestamp, const QString& logType, const QString& logLevel, const QString& content, int userId, int deviceId);
    // 内部导出日志为CSV函数
    bool exportLogsToCSVInternal(QSqlDatabase& db, const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType);
    // 内部导出日志为文本函数
    bool exportLogsToTextInternal(QSqlDatabase& db, const QString& filePath, const QString& startTime, const QString& endTime, const QString& logType);
};

#endif // LOGMANAGER_H
